package com.summer.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.summer.common.jsonTransfer.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

@Slf4j
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SpringMvcSupport extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始映射静态资源");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }

    /**  TODO：
     *      扩展springMvc的消息转换器。当导入jackson坐标并配置注解驱动时，默认使用Jackson自带的
     *   MappingJackson2HttpMessageConverter，可以通过设置此对象的属性值设置自定义消息转换器，
     *   这里的自定义消息转换器为common包下的JacksonObjectMapper类。
     *   TODO: 转换器作第二根节点做笔记
     * @param converters 用于把自定义消息转换器放在前面防止其他消息转换器覆盖
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置自定义对象映射器，底层使用Jackson向java序列化为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 将上面配置好的消息转换器追加到Mvc框架的转换器集合中，并把他放在前面
        converters.add(0,messageConverter);
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("瑞吉外卖")
                .version("1.0")
                .description("瑞吉外卖接口文档")
                .build();
    }

    @Bean
    public Docket createRestApi() {
        // 文档类型
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.summer.controller"))  // TODO 改路径
                .paths(PathSelectors.any())
                .build();
    }


}
